/*
 * Copyright (c) 2024 iSOFT INFRASTRUCTURE SOFTWARE CO., LTD.
 * easyAda is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */


#include <stdlib/assert.h>
#include <stdlib/string.h>
#include <core/task.h>
#include <uapi/ipcbuffer.h>

void ipcbuffer_partial_transfer(void *_dst, void *_src, unsigned long tag)
{
    tcb_t *dst = _dst;
    tcb_t *src = _src;

    ipcbuffer_t *dbuf;
    ipcbuffer_t *sbuf;
    unsigned int len;

    unsigned long *dmsgs;
    unsigned long *smsgs;

    assert(tcb_is_valid(dst) && tcb_is_valid(src));

    dbuf = task_get_ipcbuffer(dst);
    sbuf = task_get_ipcbuffer(src);

    dmsgs = &((ipcbuffer_get_msgs(dbuf))[6]);
    smsgs = &((ipcbuffer_get_msgs(sbuf))[6]);

    if (msgtag_get_len(tag) <= 6U) {
        return;
    } else {
        len = msgtag_get_len(tag) - 6U;
    }

    if (len <= (unsigned int)(IPC_MAX_MSGWORDS - 6)) {
        (void)memcpy(dmsgs, smsgs, len * sizeof(unsigned long));

    } else {
        dprintf("Warning: too many messages words to copy!\n");
    }
}

void ipcbuffer_regs_transfer(void *_dst, unsigned long tag, unsigned long m0, unsigned long m1, unsigned long m2,
                             unsigned long m3, unsigned long m4, unsigned long m5)
{
    tcb_t *dst = _dst;

    assert(tcb_is_valid(dst));

    ipcbuffer_t *buf = task_get_ipcbuffer(dst);

    ipcbuffer_save(buf, tag, m0, m1, m2, m3, m4, m5);
}

void ipcbuffer_full_transfer(void *_dst, void *_src)
{
    tcb_t *dst = _dst;
    tcb_t *src = _src;

    unsigned long *msgs;
    unsigned long  tag;
    ipcbuffer_t   *from;

    assert(tcb_is_valid(dst) && tcb_is_valid(src));

    from = task_get_ipcbuffer(src);
    msgs = ipcbuffer_get_msgs(from);
    tag  = ipcbuffer_get_tag(from);

    ipcbuffer_regs_transfer(dst, tag, msgs[0], msgs[1], msgs[2], msgs[3], msgs[4], msgs[5]);

    if (ipcbuffer_get_msglen(from) > 6U) {
        ipcbuffer_partial_transfer(dst, src, tag);
    }
}
